package net.htjs.mobile.qxoa;

import java.io.File;
import java.io.RandomAccessFile;
import java.util.Random;

import net.htjs.mobile.qxoa.apn.util.ApnUtility;
import net.htjs.mobile.qxoa.gw.ListGwWebView;
import net.htjs.mobile.qxoa.gw.Myinfodata;
import net.htjs.mobile.qxoa.util.FileService;
import net.htjs.mobile.qxoa.util.L;
import net.htjs.mobile.qxoa.util.Util;
import net.htjs.mobile.qxoa.util.UtilIntent;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.ProgressDialog;
import android.app.Service;
import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TabHost;

public class TabMainActivity extends TabActivity implements
		OnCheckedChangeListener {
	public TabHost mHost;
	private RadioGroup radioderGroup;
	private static String TAG="tabmain";
	RadioButton radioButton;
	// VPN连接服务相关
	private BroadcastReceiver stateBroadcastReceiver;
	
	private ApnUtility apnutility = null;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.tabhost);

		
		mHost = this.getTabHost();
		
		s_thisversion = getResources().getText(R.string.version).toString();
		s_preurl = getResources().getText(R.string.urlheader).toString();
		
		
		Intent intent = new Intent();
		Bundle bundle = new Bundle(); //
		bundle.putString(L.LX, L.Nine.DZGG); //
		 
		intent.setClass(TabMainActivity.this, ListGwWebView.class);
		intent.putExtras(bundle);
		mHost.addTab(mHost.newTabSpec("ONE").setIndicator("ONE")
				.setContent(new Intent(this, nineActivity.class)));
		mHost.addTab(mHost.newTabSpec("TWO").setIndicator("TWO")
				.setContent(intent));

		
		radioderGroup = (RadioGroup) findViewById(R.id.main_radio);
		radioderGroup.setOnCheckedChangeListener(this);
		mHost.setCurrentTabByTag("ONE");
		radioButton=(RadioButton)findViewById(R.id.radio_button1); 
		radioButton.setChecked(true);

		
		apnutility = new ApnUtility(this);
		
			if(L.isNotUseWIFI){
				mMainWifi=(WifiManager)getApplicationContext().getSystemService(Service.WIFI_SERVICE);
				registerReceiversWIFI();
			}
	}
	
	String s_thisversion=null;
	String s_preurl=null;
	public void updateNewVersion(){
		Util.Tag("开始检查更新 ", this.getApplicationContext());
		
		Myinfodata mi=new Myinfodata();
		final Myinfodata myinfo = mi.getmyinfodata();
		if (myinfo.NewVersion != null) {
			if (myinfo.NewVersion.compareTo(s_thisversion)>0) {
				Util.dialog(TabMainActivity.this, "新版本已发布，是否升级？", "立即升级", "以后再升级", TabMainActivity.this,
						"updateApp", new Object[]{myinfo}, TabMainActivity.this, null, null, false);
				
			}else{
				L.l("不需要更新");
			}
			 
		}else{
			L.l("取得版本信息异常");
		}
	}
	public void updateApp(Myinfodata myinfo){
		 
		if(L.LocationToInstall){
			dowloadDir="/sdcard/ideasdownload/";
		}
	    filePath = dowloadDir +  "nyoa" + myinfo.NewVersion + ".apk";
		this.download(myinfo.DownUrl, filePath);
	}

	public void onCheckedChanged(RadioGroup group, int checkedId) {
		switch (checkedId) {
		case R.id.radio_button1:
			mHost.setCurrentTabByTag("ONE");
			break;
		case R.id.radio_button0:
			mHost.setCurrentTabByTag("TWO");
			break;
		default:
			break;
		}
	}
	 
	public void finish4Cancel(){
		
		super.finish();
	}
	
	public void finish(){
		
		if(L.isNotUseWIFI)unregisterReceiver(mWifiStateReceiver);
		if(L.isUseAPN)apnutility.StopYidongApn();
		super.finish();
	}
	private void unregisterReceivers() {
		if (stateBroadcastReceiver != null) {
			if(L.isNotUseWIFI)unregisterReceiver(stateBroadcastReceiver);
		}
	}
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN) {
			switch (keyCode) {
			case KeyEvent.KEYCODE_BACK:
				if(L.isUseAPN)apnutility.StopYidongApn();
				super.finish();
				break;
            default:
            	break;
			}

		}
		return super.onKeyDown(keyCode, event);
	}
	WifiStateReceiver mWifiStateReceiver=null;
	public void registerReceiversWIFI(){
		 mWifiStateReceiver = new WifiStateReceiver();

	     registerReceiver(mWifiStateReceiver, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
	}
	
	int[] WIFI_STATES={0,1,2,3,4};
	class WifiStateReceiver extends BroadcastReceiver {     
		   public void onReceive(Context c, Intent intent) {
		      Bundle bundle = intent.getExtras();
		      int oldInt = bundle.getInt("previous_wifi_state");
		      int newInt = bundle.getInt("wifi_state");
		      String oldStr = (oldInt>=0 && oldInt<WIFI_STATES.length) ?WIFI_STATES[oldInt]+"" :"?";
		      String newStr = (newInt>=0 && oldInt<WIFI_STATES.length) ?WIFI_STATES[newInt]+"" :"?";
		      Log.e(TAG, "oldS="+oldStr+", newS="+newStr);
		      if(newInt==WifiManager.WIFI_STATE_DISABLED || newInt==WifiManager.WIFI_STATE_ENABLED) {
		         onWifiStateChange();  // define this function elsewhere!
		      }
		     }
		}
	WifiManager mMainWifi=null;
	private void onWifiStateChange() {
		if(L.isNotUseWIFI)return ;
        String ip_str = "";

        WifiInfo info = mMainWifi.getConnectionInfo();
        if(info != null) {
          int ipaddr = info.getIpAddress();
          ip_str = " (ip="+StringizeIp(ipaddr)+")";
        }
       

       if(mMainWifi.isWifiEnabled()==true)
    	   mMainWifi.setWifiEnabled(false);

	}
	public static String StringizeIp(int ip) {
		  int ip4 = (ip>>24) & 0x000000FF;
		  int ip3 = (ip>>16) & 0x000000FF;
		  int ip2 = (ip>> 8 )& 0x000000FF;
		  int ip1 = ip       & 0x000000FF;
		  return Integer.toString(ip1) + "." + ip2 + "." + ip3 + "." + ip4;
	}
	
	ProgressDialog progressDialog, xh_pDialog;
    int xh_count;
    
    protected static String dowloadDir = Environment.getExternalStorageDirectory() + "/ideasdownload/";
    
    protected String filePath = "";
    
	public void download(final String url, String fileName) {
		
		
        /*
         * 下载进度条初始化
         */
        xh_count = 0;

        // 创建ProgressDialog对象
        xh_pDialog = new ProgressDialog(TabMainActivity.this);

        // 设置进度条风格，风格为长条形的
        xh_pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

        xh_pDialog.setTitle("下载提示");
        xh_pDialog.setMessage("下载文件进度");
        xh_pDialog.setIndeterminate(false);
        xh_pDialog.setProgress(100);
        xh_pDialog.setIcon(R.drawable.logonyoa);

        xh_pDialog.setCancelable(true);

        xh_pDialog.show();

        new Thread() {
                @Override
                public void run() {
                        try {
                                while (xh_count>=0&&xh_count < 100) {
                                        // 由线程来控制进度
                                        xh_pDialog.setProgress(xh_count);
                                        Thread.sleep(100);
                                }
                                if(xh_count<0){
                                	Util.dialog(TabMainActivity.this, "下载失败，是否重新下载？",
                                            "重新下载", "取消", TabMainActivity.this, "download",
                                            new String[] { url, filePath },
                                            null, "openFile", new String[] {
                                                            url, filePath }, false);
                                	
                                }else{
                                	xh_pDialog.cancel();
                                    Thread.sleep(500);
                                    Intent intent = UtilIntent.getApkIntent(filePath);
                                    startActivity(intent);
                                }
                                
                        } catch (Exception e) {
                                xh_pDialog.cancel();
                        }
                }
        }.start();
        // 获取SD卡目录
        File file = new File(dowloadDir);
        // 创建下载目录
        if (!file.exists()) {
                file.mkdirs();
        }

        // 读取下载线程数，如果为空，则单线程下载
        int downloadTN = 1;

        new downloadTask(url, Integer.valueOf(downloadTN), fileName).start();
}

/**
 * @author ideasandroid 主下载线程
 */
public class downloadTask extends Thread {
        protected int blockSize, downloadSizeMore;
        private int threadNum = 5;
        String urlStr, threadNo, fileName;

        public downloadTask(String urlStr, int threadNum, String fileName) {
                this.urlStr = urlStr;
                this.threadNum = threadNum;
                this.fileName = fileName;
        }

        @Override
        public void run() {
        		Log.d("ListView", urlStr);
        		Log.d("ListView", fileName);
                try {
                        HttpPost request = new HttpPost(urlStr);
                        DefaultHttpClient client = new DefaultHttpClient();
                        HttpResponse httpResponse = client.execute(request);

                        File file = new File(fileName);

                        RandomAccessFile fos = new RandomAccessFile(file, "rw");
                        fos.write(EntityUtils.toByteArray(httpResponse.getEntity()));
                        byte[] ab = new byte[1024];
                        fos.read(ab, 0, 1024);
                        System.out.println(new String(ab));
                        fos.close();

                        xh_count = new Random().nextInt(30) + 20;

                        sleep(300);
                        xh_count = new Random().nextInt(50) + 20;

                        sleep(300);
                        xh_count = new Random().nextInt(70) + 20;

                        sleep(300);
                        xh_count = 100;
                        sleep(300);

                } catch (Exception e) {
                		xh_count=-1;
                        e.printStackTrace();
                }

        }
}
}
